/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "myled.h"
#include "stdio.h"
#include <string.h>


#include "FreeRTOS.H"
#include "task.h"
#include "queue.h"
#include "event_groups.h"  /*事件组*/
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* 任务句柄 */
TaskHandle_t LED2Task_Handler;

/* 队列句柄 */
QueueHandle_t xQueue1; 

EventGroupHandle_t  Event_groups1;

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void LED2_task(void)
{
		while(1)
		{
				HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10,GPIO_PIN_SET);
				vTaskDelay(100);
				HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10,GPIO_PIN_RESET);
				vTaskDelay(900);
		}
}

int fputc(int ch , FILE *f )
{
	 while((USART2->SR & (1<<7))==0);
	 USART2->DR=ch;
	 return ch;
}
/*使用事件组完成同步*/

void task1_function(void)/*任务1*/
{ 
	  int sum;
		while(1)
		{
			for(int i=0;i<100000;i++)
			sum++;
      xQueueSend(xQueue1,&sum,0);/*写入队列1时，队列满了就不写不等待*/
			xEventGroupSetBits(Event_groups1,(1<<0));/*写入事件组bit0*/
			sum=0;
			vTaskDelay(1);
		}
}
void task2_function(void)/*任务2*/
{ 
	  int sum=0;
		while(1)
		{
      for(int i=0;i<100000;i++)
			sum--;
			xQueueSend(xQueue1,&sum,0);
			xEventGroupSetBits(Event_groups1,(1<<1));
			sum=0;
			vTaskDelay(1);
		}
}
void task3_function(void)/*任务3，实现同步互斥的功能*/
{   
	  int sum1,sum2;
		while(1)
		{  /*
			  只接收并打印一个队列数据然后用pdfalse会有问题，数据错乱（接收的任务优先级最高就行）。
			  当12先执行，执行3时，就是一个循环队列里面已经写了两个数据了，
			  但是3只读取了一个，就会出现问题，打印也只会打印出一个，pdfalse通常用于保护的检测，
			  当任意一个错误触发时，只要调度这个任务就报错
			*/
//			 xEventGroupWaitBits(Event_groups1,(1<<0|1<<1),pdTRUE,pdTRUE,portMAX_DELAY);//等到事件全部完成
//			 xQueueReceive(xQueue1,&sum1,0);                   /*获取队列中的数据*/
//		   xQueueReceive(xQueue1,&sum2,0);                 /*获取队列中的数据*/
//			 printf("%d    %d\r\n",sum1,sum2);               /*串口打印打印对应的数据*/ 
			
			 xEventGroupWaitBits(Event_groups1,(1<<0|1<<1),pdTRUE,pdFALSE,portMAX_DELAY);//等到事件全部完成
			 xQueueReceive(xQueue1,&sum1,0);                   /*获取队列中的数据*/

			 printf("%d    \r\n",sum1);               /*串口打印打印对应的数据*/
	
		}
}
/*使用事件组同步点*/
void task4_function(void *ch)/*任务1*/
{   
	  int sum=0;
		while(1)
		{
			for(uint16_t i=0;i<50000;i++)
			sum++;
			printf("Task4 :%s\r\n",(char *)ch);
			xEventGroupSync(Event_groups1,(1<<0),(1<<0)|(1<<1)|(1<<2),portMAX_DELAY);
			/*同步点 A完成后，要等待A、B、C同时完成才能执行下一个语句吃饭，否则一直阻塞*/
			printf("Task4 eating\r\n");
			sum=0;
			vTaskDelay(100);
			/*
			优先级不同要阻塞，不然等待完成后Task eating后直接循环知道同步等待
			高优先级先执行，只有高优先级阻塞的时候低优先级才能执行
			*/
		}
}
void task5_function(void *ch)/*任务1*/
{ 
	  int sum=0;
		while(1)
		{
			for(uint16_t i=0;i<50000;i++)
			sum++;
			printf("Task5 :%s\r\n",(char *)ch);
			xEventGroupSync(Event_groups1,(1<<1),(1<<0)|(1<<1)|(1<<2),portMAX_DELAY);
			printf("Task5 eating\r\n");
			sum=0;
			vTaskDelay(100);
		}
}
void task6_function(void *ch)/*任务1*/
{ 
	  int sum=0;
		while(1)
		{
			for(uint16_t i=0;i<50000;i++)
			sum++;
			printf("Task6 :%s\r\n",(char *)ch);
			xEventGroupSync(Event_groups1,(1<<2),(1<<0)|(1<<1)|(1<<2),portMAX_DELAY);
			printf("Task6 eating\r\n");
			sum=0;
			vTaskDelay(100);
		}
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */
  
  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */
   
  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */
  myled_config();
	/*创建队列*/
	xQueue1=xQueueCreate(2,sizeof(int));
	if(xQueue1==0)
	{
		 printf(" NO xQueue1 ");
	}
  /*创建事件组*/
	Event_groups1=xEventGroupCreate();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
     
//  xTaskCreate((TaskFunction_t )LED2_task,            //任务函数
//              (const char*    )"LED2_task",          //任务名称
//              (uint16_t       )128,                  //栈大小
//              (void*          )NULL,                 //传入参数
//              (UBaseType_t    )0,                    //优先级
//              (TaskHandle_t*  )&LED2Task_Handler);   //任务句柄    
							
   xTaskCreate((TaskFunction_t )task1_function,"task1_function",128,NULL,1,NULL);   
	 xTaskCreate((TaskFunction_t )task2_function,"task2_function",128,NULL,1,NULL);	
//	 xTaskCreate((TaskFunction_t )task3_function,"task3_function",128,NULL,1,NULL);	
   xTaskCreate((TaskFunction_t )task3_function,"task3_function",128,NULL,2,NULL);	

//   xTaskCreate((TaskFunction_t )task4_function,"task4_function",128,"Cook",1,NULL);
//	 xTaskCreate((TaskFunction_t )task5_function,"task5_function",128,"set a table",2,NULL);	
//   xTaskCreate((TaskFunction_t )task6_function,"task6_function",128,"cut up vegetables",3,NULL);		
   vTaskStartScheduler();                             //启动调度器                    
   
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */

  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 90;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Activate the Over-Drive mode
  */
  if (HAL_PWREx_EnableOverDrive() != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
